<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Order\Service\OrderMerchantUseService;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Statistics\Service\StatisticsService;
use Illuminate\Support\Str;

/**
 * app-支付明细统计
 */
class ExportAppPayService extends BaseExportService
{
    private string $localPath = '';

    public function query(): self
    {
        $shopId  = (int)($this->params['shopId'] ?? 0);
        $startAt = $this->params['showStartAt'] ?? time();
        $endAt   = $this->params['showEndAt'] ?? time();

        $header  = [
            '支付渠道',
            '流水号',
            '金额',
            '时间',
            '收退状态',
        ];
        $content = [];

        (new OrderMerchantUseService([$shopId]))
            ->payUnionListsDefine($startAt, $endAt)
            ->each(function ($item) use (&$content) {
                $content[] = [
                    'payTypeText'   => $item['payTypeText'],
                    'orderId'       => $item['bizId'] ?: $item['orderId'],
                    'payPrice'      => (string)round($item['payPrice'] / 100, 2),
                    'createdAt'     => date('Y-m-d H:i:s', $item['createdAt']),
                    'payStatusText' => $item['payStatusText'],
                ];
            });

        $this->localPath = sys_get_temp_dir() . '/' . Str::random();
        self::streamExport($content, $shopId, $startAt, $endAt, $this->localPath);


        return $this;
    }

    public function path(): string
    {
        return $this->upload($this->localPath);
    }


    public static function streamExport(
        array $dataArr,
        int $shopId,
        string $startAt,
        string $endAt,
        string $path
    ): array {

        $shopInfo = ShopService::getShopInfo($shopId);

        $data = self::getToChange($dataArr, $shopInfo);

        // 生成excel
        $fileType = ExportDownloadModel::FILE_TYPE_APP_PAY;
        $client   = ExportDownloadModel::CLIENT_TYPE_APP;
        $fileName = (new ExportDownloadModel())->buildFileName($shopId, strtotime($startAt), strtotime($endAt),
            $fileType, $client);

        StatisticsService::spreadsheetExcel([
            [
                'info'  => $data['info'],
                'title' => $data['title'],
                'rows'  => iterator_to_array($data['rows']),// 把yield转成数组
            ]
        ], $fileName, $path);

        return $data;
    }

    /**
     * 导出信息组装
     * @param $storeOrderList
     * @param $shopInfo
     * @return array
     */
    public static function getToChange(
        $storeOrderList,
        $shopInfo
    ): array {
        $rows = self::yieldOrderInfo($storeOrderList);
        return [
            'title' => '支付明细统计',
            'info'  => [
                '门店'   => $shopInfo['name'],
                '门店编码' => str_pad($shopInfo['shopCode'],
                    ShopCodeEnum::CODE_TEXT[ShopCodeEnum::LEADING_ZERO], "0", STR_PAD_LEFT),//门店编号
            ],
            'rows'  => $rows
        ];
    }

    public static function yieldOrderInfo($orderList): \Generator
    {
        $rows = [
            '支付渠道',
            '流水号',
            '金额',
            '时间',
            '收退状态',
        ];
        yield $rows;
        foreach ($orderList as $key => $value) {
            $rows[$key + 1] = [
                $value['payTypeText'],
                $value['orderId'] . ' ',
                $value['payPrice'],
                $value['createdAt'],
                $value['payStatusText'],
            ];
            yield $rows[$key + 1];
        }
    }
}
